package com.yuanqiao.insight.modules.notice.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuanqiao.insight.modules.notice.entity.JsonValue;
import com.yuanqiao.insight.modules.notice.entity.SysNoticeConfig;
import com.yuanqiao.insight.modules.notice.entity.SysNoticeTemplate;
import com.yuanqiao.insight.modules.notice.mapper.SysNoticeTemplateMapper;
import com.yuanqiao.insight.modules.notice.service.ISysNoticeConfigService;
import com.yuanqiao.insight.modules.notice.service.ISysNoticeTemplateService;
import com.yuanqiao.insight.modules.notice.service.impl.SysNoticeTemplateServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.insight.common.api.vo.Result;
import com.insight.common.aspect.annotation.AutoLog;
import com.insight.common.mq.RedisMq;
import com.insight.common.mq.stream.Streams;
import com.insight.common.system.base.controller.JeecgController;
import com.yuanqiao.insight.acore.system.service.ISysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 通知模板
 * @Author: jeecg-boot
 * @Date: 2021-05-28
 * @Version: V1.0
 */
@Api(tags = "通知模板")
@RestController
@RequestMapping("/sys/notice/template")
@Slf4j
public class SysNoticeTemplateController extends JeecgController<SysNoticeTemplate, ISysNoticeTemplateService> {
    @Autowired
    private SysNoticeTemplateServiceImpl sysNoticeTemplateService;
    @Autowired
    private SysNoticeTemplateMapper sysNoticeTemplateMapper;
    @Autowired
    private ISysNoticeConfigService noticeConfigService;
    @Autowired
    private RedisMq redisMq;
    @Autowired
    ISysDictService sysDictService;

    /**
     * 分页列表查询
     *
     * @param sysNoticeTemplate
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "通知模板-分页列表查询")
    @ApiOperation(value = "通知模板-分页列表查询", notes = "通知模板-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(SysNoticeTemplate sysNoticeTemplate,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<SysNoticeTemplate> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(sysNoticeTemplate.getTemplateName())) {
            queryWrapper.like("template_name", sysNoticeTemplate.getTemplateName());
        }
        queryWrapper.eq("delflag", 0);
        queryWrapper.orderByDesc("create_time");
        Page<SysNoticeTemplate> page = new Page<SysNoticeTemplate>(pageNo, pageSize);
        IPage<SysNoticeTemplate> pageList = sysNoticeTemplateService.page(page, queryWrapper);
        for (SysNoticeTemplate record : pageList.getRecords()) {
            final SysNoticeConfig noticeConfig = noticeConfigService.getById(record.getNoticeConfigId());
            record.setNoticeConfigId_dictText(noticeConfig.getConfigName());
        }
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param sysNoticeTemplate
     * @return
     */
    @AutoLog(value = "通知模板-添加")
    @ApiOperation(value = "通知模板-添加", notes = "通知模板-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody SysNoticeTemplate sysNoticeTemplate) {
        sysNoticeTemplate.setDelflag(0);
        //setBusiness(sysNoticeTemplate);
        sysNoticeTemplateService.save(sysNoticeTemplate);

        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param sysNoticeTemplate
     * @return
     */
    @AutoLog(value = "通知模板-编辑")
    @ApiOperation(value = "通知模板-编辑", notes = "通知模板-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody SysNoticeTemplate sysNoticeTemplate) {
        //setBusiness(sysNoticeTemplate);
        sysNoticeTemplateService.updateById(sysNoticeTemplate);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "通知模板-通过id删除")
    @ApiOperation(value = "通知模板-通过id删除", notes = "通知模板-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
//		SysNoticeTemplate byId = sysNoticeTemplateService.getById(id);
//		sysNoticeExtendMapper.delByConfigId(byId.getNoticeConfigId());
        sysNoticeTemplateService.removeById(id);


        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "通知模板-批量删除")
    @ApiOperation(value = "通知模板-批量删除", notes = "通知模板-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.sysNoticeTemplateService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "通知模板-通过id查询")
    @ApiOperation(value = "通知模板-通过id查询", notes = "通知模板-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(String id) {
        if (id == null) {
            return null;
        }
        SysNoticeTemplate sysNoticeTemplate = sysNoticeTemplateService.findAllById(id);
        if (sysNoticeTemplate == null) {
            return Result.error("未找到对应数据");
        }

        return Result.OK(sysNoticeTemplate);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param sysNoticeTemplate
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SysNoticeTemplate sysNoticeTemplate) {
        return super.exportXls(request, sysNoticeTemplate, SysNoticeTemplate.class, "通知模板");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SysNoticeTemplate.class);
    }


    /**
     * 第一层
     *
     * @param
     * @return
     */
//	 @AutoLog(value = "通知模板-模式")
    @ApiOperation(value = "通知模板-模式", notes = "通知模板-模式")
    @GetMapping(value = "/alarm")
    public Result<?> alarm() {
//		JsonValue jsonValue = new JsonValue();
        JsonValue jsonValue1 = new JsonValue();
        JsonValue jsonValue2 = new JsonValue();
        JsonValue jsonValue3 = new JsonValue();
//		jsonValue.setType("alarm");
//		jsonValue.setCode("告警");
        jsonValue1.setType("process");
        jsonValue1.setCode("流程");// 未使用
        jsonValue2.setType("businessType");
        jsonValue2.setCode("业务流程");
        jsonValue3.setType("autoInspection");
        jsonValue3.setCode("智能巡检");// 未使用

        List<JsonValue> lists = new ArrayList<>();
//		lists.add(jsonValue);
        lists.add(jsonValue1);
        lists.add(jsonValue2);
        lists.add(jsonValue3);
        return Result.OK(lists);
    }

    /**
     * 第二层
     *
     * @param
     * @return
     */
//	 @AutoLog(value = "通知模板-模式")
    @ApiOperation(value = "通知模板-模式", notes = "通知模板-模式")
    @GetMapping(value = "/level")
    public Result<?> level() {
        List<JsonValue> levels = sysNoticeTemplateMapper.findLevel(); // 级别

        return Result.OK(levels);
    }

    /**
     * 第三层
     * 告警策略产品分类-产品-设备树 查询所有产品分类
     *
     * @param
     * @return
     */
//	 @AutoLog(value = "通知模板-模式")
    @ApiOperation(value = "通知模板-模式", notes = "通知模板-模式")
    @GetMapping(value = "/assets")
    public Result<?> assets() {
        List<JsonValue> assetss = sysNoticeTemplateMapper.findAllAssets();//资产id

        return Result.OK(assetss);
    }

    /**
     * 第四层
     * 告警策略产品分类-产品-设备树 根据产品分类ID查询其下所有产品
     *
     * @param
     * @return
     */
//	 @AutoLog(value = "通知模板-模式")
    @ApiOperation(value = "通知模板-模式", notes = "通知模板-模式")
    @GetMapping(value = "/productList")
    public Result<?> productList(@RequestParam("assetsId") String assetsId) {
        List<JsonValue> assets = sysNoticeTemplateMapper.findAssetsByAssetsId(assetsId);
        List<JsonValue> productLists = sysNoticeTemplateMapper.findProByAssetsId(assetsId); // 产品id

        List<JsonValue> result = new ArrayList<>();
        result.addAll(assets);
        result.addAll(productLists);
        return Result.OK(result);
    }

    /**
     * 第五层
     * 告警策略产品分类-产品-设备树 根据产品ID查询其下所有设备
     *
     * @param
     * @return
     */
    @AutoLog(value = "通知模板-模式")
    @ApiOperation(value = "通知模板-模式", notes = "通知模板-模式")
    @GetMapping(value = "/devList")
    public Result<?> devList(@RequestParam("productId") String productId) {
        List<JsonValue> devLists = sysNoticeTemplateMapper.findDevByProId(productId); // 设备id
        return Result.OK(devLists);
    }

    /**
     * 告警模板新增修改界面关联通知模板下拉数据
     *
     * @return
     */
    @AutoLog(value = "通知模板-下拉选择数据")
    @ApiOperation(value = "通知模板-下拉选择数据", notes = "通知模板-下拉选择数据")
    @GetMapping(value = "/templateList")
    public Result<?> templateList(@RequestParam("business") String business) {
        List<JsonValue> templateList = sysNoticeTemplateMapper.findTemplateByBusiness(String.format("%%%s%%", shortMd5(business)));
        return Result.OK(templateList);
    }

    /**
     * @param testSend templateCode 通知模板编码,即id
     *                 dataJson   消息数据，格式：
     *                 {
     *                 "support":"support",要使用的通知方式,查看枚举NoticeType
     *                 "par":"par" 对模板内容的替换数据
     *                 }
     * @return
     */
    @AutoLog(value = "通知模板-发送通知")
    @ApiOperation(value = "通知模板-发送通知", notes = "通知模板-发送通知")
    @PostMapping(value = "/sendNotice")
    public Result<Object> sendNotice(@RequestBody Map<String, String> testSend) {
        final String templateCode = testSend.get("templateCode");
        String dataJson = testSend.get("dataJson");
        String sendTo = testSend.get("sendTo");
        SysNoticeTemplate sysNoticeTemplate = sysNoticeTemplateService.getById(templateCode);
        if (sysNoticeTemplate != null) {
            if (StringUtils.isEmpty(dataJson)) {
                dataJson = "{}";
            }
            JSONObject data = JSON.parseObject(dataJson);
            //获取通知配置
            JSONObject noticeConfig = noticeConfigService.getNoticeConfig(sysNoticeTemplate.getNoticeConfigId());

            //获取通知模板设置
            JSONObject template = JSON.parseObject(sysNoticeTemplate.getTemplate());
            template.put("par", data);
            if (StringUtils.isNotEmpty(sendTo)) {
                template.put("sendTo", sendTo);
            }
            //组装消息体
            JSONObject msgData = new JSONObject();
            msgData.putAll(noticeConfig);
            msgData.put("template", template);
            msgData.put("isPar", CollUtil.isNotEmpty(data));
            redisMq.publish(Streams.NOTICE, msgData);
            return Result.OK();
        }
        return Result.error("未找到通知模板");
    }

    private static String shortMd5(String data) {
        System.out.printf(data + ": ");
        Digester md5 = new Digester(DigestAlgorithm.MD5);
        final String encode = md5.digestHex(data);
        return encode.substring(8, 24).toUpperCase();
    }

    private void setBusiness(SysNoticeTemplate sysNoticeTemplate) {
        JSONArray jsonArray = JSON.parseArray(sysNoticeTemplate.getBusiness());
        for (int i = 0; i < jsonArray.size(); i++) {
            final String business = jsonArray.getString(i);
            jsonArray.set(i, shortMd5(business));
        }
        sysNoticeTemplate.setBusiness(jsonArray.toJSONString());
    }

    public static void main(String[] args) {
        System.out.println(shortMd5("/alarmManage/alarmTemplate/AlarmTemplateManage"));
        System.out.println(shortMd5("/autoInspection/DevopsAutoInspectionManage"));
        System.out.println(shortMd5("/devicesystem/DeviceInfoMange"));
        System.out.println(shortMd5("/vmware/ESXI/DeviceInfoMange"));
        System.out.println(shortMd5("/cloudPlatform/cloudInfoMange"));
        System.out.println(shortMd5("/networkManagement/networkDevice/DeviceInfoManagement"));
        System.out.println(shortMd5("/businessMonitoring/businessOverview/businessOverviewManagement"));
        System.out.println(shortMd5("/assets/AssetsManagement"));
        System.out.println(shortMd5("/alarmManage/assetsAlarm/AssetsAlarmManage"));
        System.out.println(shortMd5("/bigscreen/syIndex"));
        System.out.println(shortMd5("/bigscreen/moduels/network-flag"));
        System.out.println(shortMd5("/bigscreen/dataAnalysisIndex"));
        System.out.println(shortMd5("/view/appTopoManage"));
        System.out.println(shortMd5("/view/networkTopo"));
        System.out.println(shortMd5("/zfnw/topo"));
    }
}
